#coding: utf8

from __future__ import unicode_literals

from flask import Flask, request, abort, jsonify
import json
from werkzeug.exceptions import Aborter
import shelve

app = Flask(__name__)

access_token = "Nvo7SFZKgxhecOia"

user_db = "user.db"


@app.route("/add", methods=['POST'])
@app.route("/update", methods=['POST'])
def add():
    resp_tpl = {"code": 4, "message": None, "data": None}
    params = valid_param()
    if isinstance(params, Aborter):
        resp_tpl.update({'message': "非法操作"})
        return jsonify(resp_tpl)
    uid,name,grade = params
    if uid is None or uid == "":
        resp_tpl.update({"message": "uid不能为空"})
        return jsonify(resp_tpl)
    s = shelve.open(user_db)
    s[str(uid)] = dict(uid=str(uid),name=name.encode("utf-8"),grade=grade.encode("utf-8"))
    s.close()
    resp_tpl.update({"code": 2})
    return jsonify(resp_tpl)

@app.route("/delete", methods=['POST'])
def delete():
    resp_tpl = {"code": 4, "message": None, "data": None}
    form = request.form
    token = form.get("token", None)
    if token != access_token:
        resp_tpl.update({'message': "非法操作"})
        return jsonify(resp_tpl)
    uid = form.get("uid")
    s = shelve.open(user_db)
    if s.has_key(str(uid)):
        s.pop(str(uid))
    resp_tpl.update({"code": 2})
    return jsonify(resp_tpl)

@app.route("/list")
def list():
    resp_tpl = {"code": 4, "message": None, "data": None}
    args = request.args
    token = args.get("token")
    if token != access_token:
        resp_tpl.update({'message': "非法操作"})
        return jsonify(resp_tpl)
    s = shelve.open(user_db)
    l = [item for (index, item) in s.iteritems()]
    s.close()
    resp_tpl.update({"code": 2, "data": l})
    return jsonify(resp_tpl)

@app.route("/show")
def show():
    resp_tpl = {"code": 4, "message": None, "data": None}
    args = request.args
    token = args.get("token")
    if token != access_token:
        resp_tpl.update({'message': "非法操作"})
        return jsonify(resp_tpl)
    uid = args.get('uid')
    s = shelve.open(user_db)
    i = {}
    if s.has_key(str(uid)):
        i = s[str(uid)]
    s.close()
    resp_tpl.update({"code": 2, "data": i})
    print resp_tpl
    return jsonify(resp_tpl)

@app.route("/clear")
def clear():
    resp_tpl = {"code": 4, "message": None, "data": None}
    args = request.args
    token = args.get("token")
    if token != access_token:
        resp_tpl.update({'message': "非法操作"})
        return jsonify(resp_tpl)
    s = shelve.open(user_db)
    s.clear()
    s.close()
    resp_tpl.update({"code": 2})
    return jsonify(resp_tpl)

def valid_param():
    form = request.form
    token = form.get("token", None)
    if token != access_token:
        return abort(403)
    uid = form.get("uid", None)
    name = form.get("name", None)
    grade = form.get("grade", None)
    return uid,name,grade

if __name__ == "__main__":
    app.run(debug=True)